package com.hanhai.zrb.backend.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IntentionService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.ResourceMatchService;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.util.BackendLoginUtil;
import com.hanhai.zrb.model.fund.vo.FundSearchVo;
import com.hanhai.zrb.model.intention.Intention;
import com.hanhai.zrb.model.intention.dto.IntentionDto;
import com.hanhai.zrb.model.intention.enums.IntentionTypeEnum;
import com.hanhai.zrb.model.project.Project;
import com.hanhai.zrb.model.resourcematch.ResourceMatchContent;
import com.hanhai.zrb.model.resourcematch.ResourceMatchResult;
import com.hanhai.zrb.model.resourcematch.ResourceMatchTypeEnum;

@Controller
@RequestMapping("/intention")
public class IntentionController extends BaseController {

	@Resource
	private IntentionService intentionService;
	
	@Resource
	private ResourceMatchService resourceMatchService;
	
	@Resource
	private ProjectService projectService;
	
	@Resource
	private FundService fundService;
	
	@RequestMapping("/index")
	public String index(Model model) {
		return "intention/index";
	}
	
	//项目，匹配资金意向
	@RequestMapping("/list")
	@ResponseBody
	public String list(IntentionDto intentionDto,Integer page,Integer rows ) {
		Map<String, Object> map = Maps.newHashMap();
		PageInfo pageInfo =intentionService.findIntentions(intentionDto, page, rows);
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return JSON.toJSONString(map);
	}
	
	//资金，匹配项目意向
	@RequestMapping("/findFundList")
	@ResponseBody
	public String findFundList(IntentionDto intentionDto,Integer page,Integer rows ) {
		Map<String, Object> map = Maps.newHashMap();
		PageInfo pageInfo =intentionService.findFundList(intentionDto, page, rows);
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return JSON.toJSONString(map);
	}
	
	@RequestMapping(value="/edit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String edit(Intention intention) {
		Map<String, Object> map = Maps.newHashMap();
		if (intentionService.updateIntention(intention)) {
			map.put("success", true);
			map.put("msg", "编辑成功!");
		}else{
			map.put("success", false);
			map.put("msg", "编辑失败!");
		}
		return JSON.toJSONString(map);
	}
	
	@RequestMapping(value="/multiHandle",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String multiHandle(String ids){
		Map<String, Object> map = Maps.newHashMap();
		BackendUser backendUser = BackendLoginUtil.getCurrentUser();
		String[] str = StringUtils.split(ids, ",");
		List<Intention> list = new ArrayList<Intention>();
		for (String id : str) {
			Intention intention = new Intention();
			intention.setId(Long.valueOf(id));
			intention.setHandlePerson(backendUser.getUserName());
			intention.setHandleTime(new Date());
			intention.setStatus(1);
			list.add(intention);
		}
		if (intentionService.batchUpdateIntention(list)) {
			map.put("success", true);
			map.put("msg", "处理成功!");
		}else{
			map.put("success", false);
			map.put("msg", "处理失败!");
		}
		return JSON.toJSONString(map);
	}
	
	@RequestMapping(value="/multiDelete",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String multiDelete(String ids) {
		Map<String, Object> map=Maps.newHashMap();
		List<Long> idList = Lists.newArrayList();
		for(String id:StringUtils.split(ids, ",")){
			idList.add(Long.parseLong(id));
		}
		if(intentionService.multiDelete(idList)){
			map.put("success", true);
			map.put("msg", "删除成功!");
		}else{
			map.put("success", false);
			map.put("msg", "删除失败!");
		}
		return JSONObject.toJSONString(map);
	}
	
	@InitBinder
	@Override
	protected void initBinder(WebDataBinder binder) throws ServletException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);

		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, true));

		CustomCollectionEditor collectionEditor = new CustomCollectionEditor(List.class, true);

		binder.registerCustomEditor(List.class, collectionEditor);
	}
	
	@RequestMapping("/showMarry")
	public ModelAndView showMarryFund(String id,Integer type,HttpServletRequest request,HttpServletResponse response) {
		String str = null;
		Long ids = null;
		if( StringUtils.isNotBlank(id)){
			ids = Long.valueOf(id);
		}
		ResourceMatchResult recommends = new ResourceMatchResult();
		List<ResourceMatchContent> recommend = new ArrayList<ResourceMatchContent>();
		//意向项目  匹配  资金
		if( type.equals(IntentionTypeEnum.project.getCode())){
			recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.INTENTION_PROJECT.getCode(), ids );
			recommend = recommends.getResourceMatchContentList();
			List<Long> list = getList(recommend);
			List<FundSearchVo> findFundSearchVo = fundService.findFundSearchVo(list);
			request.setAttribute("queryByIdsList", findFundSearchVo);
			str = "redirect:/project/showMarryFund?type="+IntentionTypeEnum.project.getCode()+"&id="+id+"";
		}else if( type.equals(IntentionTypeEnum.fund.getCode())){//意向资金  匹配项目
			recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.INTENTION_FUND.getCode(), ids );
			recommend = recommends.getResourceMatchContentList();
			List<Long> list = getList(recommend);
			List<Project> queryByIdList = projectService.queryByIdsList(list);
			request.setAttribute("queryByIdsList", queryByIdList);
			str =  "redirect:/fundBack/showMarryProject?type="+IntentionTypeEnum.fund.getCode()+"&id="+id+"";
		}
		
        return  new ModelAndView(str);
	}

	private List<Long> getList(List<ResourceMatchContent> recommend) {
		List<Long> list = new ArrayList<Long>() ;
		for (int i = 0; i < recommend.size(); i++) {
			list.add(recommend.get(i).getBizid());
		}
		return list;
	}
}
